<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">

    <meta charset="UTF-8">
    <title>年度报告</title>
    <link rel="stylesheet" type="text/css" media="screen" href="../../css/bootstrap.min.css">
    <link rel="stylesheet" type="text/css" media="screen" href="../../css/dataTables.bootstrap.min.css">
    <link rel="stylesheet" href="../../layui/css/layui.css" media="all"/>
    <link rel="stylesheet" href="../../css/global.css" media="all"/>
    <style>
        #popSearchRoleTest .layui-form-select dl {
            max-height: 170px;
        }

        #popSearchRoleTest .layui-form-select dl dd {
            font-size: 18px;
        }

        #uploadFile {
            overflow-y: hidden;
        }
    </style>
</head>
<body>
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-12 page-container">
    <header class="form-filter-wrap">
        <form class="layui-form form-inline" onsubmit="return false">
            <div class="form-group">
                <div class="form-filter">
                    <div class="form-inner">
                        <label class="layui-form-label" for="">单位：</label>
                        <div class="layui-input-inline">
                            <select multiple lay-omit id="branch" lay-search >
                                <option value="">请选择</option>
                            </select>
                        </div>
                    </div>
                    <div class="form-inner">
                        <label class="layui-form-label" for="">巡察年度：</label>
                        <div class="layui-input-inline">
                            <select multiple lay-omit id="startPatrolTime">
                                <option value="">请选择</option>
                            </select>
                        </div>
                    </div>
                    <button id="searchBt" class="layui-btn layui-btn-sm"><i class="layui-icon">&#xe615;</i>搜索
                    </button>
                </div>
                <div class="form-btn">
                    <button type="button" class="layui-btn layui-btn-sm" id="up"><i class="layui-icon"></i>上传年度报告
                    </button>
                    <button class="layui-btn layui-btn-sm" type="button" id="down">
                        <i class="layui-icon"></i> 查看年度报告
                    </button>
                    <button class="layui-btn layui-btn-sm" type="button" id="del">
                        <i class="layui-icon"></i> 删除
                    </button>
                </div>
            </div>

        </form>
    </header>

    <div class="content-container">
        <div class="widget-body no-padding">
            <table id="dt-table" class="table table-striped table-bordered table-hover" style="width:100%">
                <thead>
                <tr>
                    <th><input type='checkbox' id='checkAll'/></th>
                    <th>单位</th>
                    <th>报告人</th>
                    <th style="width: 70px">巡察年度</th>
                    <th>公司年度整体报告</th>
                    <th>录入时间</th>
                </tr>
                </thead>
                <tbody>
                </tbody>
            </table>
        </div>
    </div>
</div>
<div class="layui-row" id="popSearchRoleTest" style="display: none">
    <div class="">
        <form class="layui-form form-container" action="">
            <div class="layui-form-item">
                <div class="layui-inline">
                    <label class="layui-form-label">单位</label>
                    <div class="layui-input-inline">
                        <select name="branchName" id="branchName" lay-verify="required" lay-filter="selectBranch">
                            <option value=""></option>
                        </select>
                    </div>
                </div>
            </div>
            <div class="layui-form-item">
                <div class="layui-inline">
                    <label class="layui-form-label">巡察年度</label>
                    <div class="layui-input-inline">
                        <select name="year" id="year" lay-verify="required" lay-filter="xmFilter">
                            <option value=""></option>
                        </select>
                    </div>
                </div>
            </div>
            <div class="layui-form-item">
                <div class="layui-inline">
                    <label class="layui-form-label"></label>
                    <button type="button" class="layui-btn " id="upload">
                        <i class="layui-icon"></i>上传附件
                    </button>
                    &nbsp
                    <button class="layui-btn" lay-submit lay-filter="saveBtn">提交</button>
                </div>
            </div>

        </form>
    </div>
</div>
<script type="text/javascript" src="../../js/libs/jquery-1.11.1.min.js"></script>
<script type="text/javascript" src="../../js/jq.js"></script>
<script type="text/javascript" src="../../js/plugin/datatables/jquery.dataTables.min.js"></script>
<script type="text/javascript" src="../../js/plugin/datatables/dataTables.bootstrap.min.js"></script>
<script type="text/javascript" src="../../js/my/permission.js"></script>
<script type="text/javascript" src="../../layui/layui.js"></script>
<script type="text/javascript" src="../../js/dict.js"></script>
<script type="text/javascript" src="../../js/plugin/jquery-download.js"></script>
<script type="text/javascript">
    var userId = $('.header-demo .layui-nav .layui-nav-item a span#userId', parent.document).text();
    /*公司*/
    layui.use(['layer', 'form', 'jquery'], function () {
        var form = layui.form;
        $.ajax({
            url: '/dropDown/getBranch',
            dataType: 'json',
            type: 'post',
            success: function (data) {
                // 使用循环遍历，给下拉列表赋值
                $.each(data, function (index, value) {
                    $('#branch').append(new Option(value.value, value.value));// 下拉菜单里添加元素
                    $('#branchName').append(new Option(value.value, value.value));// 下拉菜单里添加元素
                });
                form.render();//重新渲染 固定写法
            }
        })
            /*年度*/
            , $.ajax({
            url: '/dropDown/getYear',
            dataType: 'json',
            type: 'post',
            success: function (data) {
                // 使用循环遍历，给下拉列表赋值
                $.each(data, function (index, value) {
                    $('#startPatrolTime').append(new Option(value.value, value.value));// 下拉菜单里添加元素
                    $('#year').append(new Option(value.value, value.value));// 下拉菜单里添加元素
                });
                form.render();//重新渲染 固定写法
            }
        })


    });


    var example;

    function init() {
        $.ajax({
            type: 'POST',
            dataType: 'text',
            url: '/mOverseeQuestions/getUser',
            contentType: "application/json; charset=utf-8",
            success: function (data) {
                console.log(data)
                /*修改*/
                if ("0" === data) {
                    $("#up").hide()
                    $("del").hide()
                }
            }
        })

        example =
            $('#dt-table').DataTable({
                    "retrieve": true,
                    "searching": false,
                    "processing": false,
                    "serverSide": true,
                    "ordering": false,
                    bAutoWidth: false,
                    "scrollX": false,
                    "scrollY": false,
                    "page": true,
                    "language": {
                        "url": "/js/plugin/datatables/Chinese.lang"
                    },
                    "ajax": {
                        "url": "/mOverseeQuestions/pool",
                        "type": "get",
                        "data": function (d) {
                            if ($("#startPatrolTime").val() != null) {
                                d.startPatrolTime = JSON.stringify($("#startPatrolTime").val());
                            }
                            if ($("#branch").val() != null) {
                                d.branch = JSON.stringify($("#branch").val());
                            }
                        },
                        "error": function (xhr, textStatus, errorThrown) {
                            var msg = xhr.responseText;
                            console.log(msg);
                            var response = JSON.parse(msg);
                            var code = response.code;
                            var message = response.message;
                            if (code == 400) {
                                layer.msg(message);
                            } else if (code == 401) {
                                localStorage.removeItem("token");
                                layer.msg("token过期，请先登录", {shift: -1, time: 1000}, function () {
                                    location.href = '/login.html';
                                });
                            } else if (code == 403) {
                                console.log("未授权:" + message);
                                layer.msg('未授权');
                            } else if (code == 500) {
                                layer.msg('系统错误：' + message);
                            }
                        }
                    },
                    "dom": "<'dt-toolbar'r>t<'dt-toolbar-footer'<'table-bottom col-sm-10 col-xs-12 hidden-xs'i><'table-bottom col-xs-12 col-sm-10' p v>>",
                    "columns": [
                        {
                            "data": "id",
                            "render": function (data, type, row, meta) {
                                return "<input type='checkbox' class='table-checkbox' onclick='childclick(" + data + ")' name='childclick' id='' value=" + data + " />";
                            }
                        },
                        {
                            "data": "branch",
                            "defaultContent": "",
                            "render": function (data, type, row, meta) {
                                return "<a href='javascript:;' ><cite>" + data + "</cite></a>"
                            }
                        },
                        {
                            "data": "oversee",
                            "defaultContent": ""
                        },
                        {"data": "overseeYear", "defaultContent": ""},
                        {"data": "path", "defaultContent": ""},

                        {"data": "createTime", "defaultContent": ""},
                    ],
                    "createdRow": function( row, data, dataIndex ) {
                        if ( data.delated === 1 ) {
                            $('td', row).css("background", "#DCDCDC");
                        }
                    },

                    "order": [[0, "asc"]]
                }
            );
        return example
    }


    // 上传附件
    $(document).on('click', '#up', function () {

        layer.open({
            type: 1,
            title: ['年度报告', 'font-weight: bold;font-size: 26px;text-align: center;'],
            shadeClose: true,
            shade: 0.7,
            id: 'uploadFile',
            area: ['500px', '380px'],
            content: $('#popSearchRoleTest'),
            success: function (layero, index) {
                layui.use(['layer', 'form', 'jquery', 'upload'], function () {
                    var form = layui.form;
                    var upload = layui.upload;

                    $('#upload').attr('disabled', true)

                    form.on('select(selectBranch)', function (data) {
                        if ($("#branchName option:selected").text() === null || $("#branchName option:selected").text() === '') {
                            $('#upload').attr('disabled', true)
                        } else {
                            $('#upload').attr('disabled', false)
                        }
                    });


                    layui.use(['layer', 'form', 'jquery', 'upload'], function () {
                        var upload = layui.upload;
                        upload.render({
                            elem: '#upload' //绑定元素
                            , url: '/mOverseeQuestions/uploadSource' //上传接口
                            , accept: 'file'
                            , multiple: true
                            , method: 'POST',
                            data: {
                                branch: $("#branchName option:selected").text()
                            },
                            done: function (res) {

                                //上传完毕回调
                                layer.msg("上传成功！");

                                var path = $("#upload").val();
                                if ( path != null && path != ''){
                                    $("#upload").val(path +','+ res.msg);
                                }else {
                                    $("#upload").val(res.msg)
                                }
                            }
                            , error: function (res) {
                                //请求异常回调
                                layer.msg("上传失败！");
                            }
                        });
                    })


                    //监听提交
                    form.on('submit(saveBtn)', function (data) {
                        if ($("#upload").val() === '' || $("#upload").val() === null){
                            layer.msg('请先上传附件')
                            return
                        }
                        // 单击之后提交按钮不可选,防止重复提交
                        var DISABLED = 'layui-btn-disabled';
                        // 增加样式
                        $('.save').addClass(DISABLED);
                        // 增加属性
                        $('.save').attr('disabled', 'disabled');

                        data.field.branchName = $("#branchName option:selected").text();//获取文本 id: 以降序排列此列
                        data.field.year = $("#year option:selected").text();//获取文本
                        data.field.file = $("#upload").val();
                        console.log(data.field)
                        $.ajax({
                            type: 'POST',
                            dataType: 'json',
                            url: '/mOverseeQuestions/saveReport',
                            contentType: "application/json; charset=utf-8",
                            data: JSON.stringify(data.field),
                            success: function (res) {
                                if (res.errorCode == 0) {
                                    layer.msg("保存成功", {
                                        icon: 1,
                                        time: 1000
                                    }, function () {
                                        layer.close(index)
                                        window.location.reload();
                                    });
                                }
                            }
                        })
                        return false;
                    });
                })
            }
        });
    })


    //下面为点击首项选中子项;子项全选,首项选中
    $('#checkAll').on('click', function () {
        if (this.checked) {
            $(this).attr('checked', 'checked')
            $("input[name='childclick']").each(function () {
                this.checked = true;
            });
        } else {
            $(this).removeAttr('checked')
            $("input[name='childclick']").each(function () {
                this.checked = false;
            });
        }
    });

    function childclick() {

        if ($(this).is(":checked") == false) {
            $("#checkAll").prop("checked", false);
        }
        if ($("input[name='childclick']:checked").length == $("input[name='childclick']").length) {
            $("#checkAll").prop("checked", true);
        }
    }


    // 附件下载
    function sleep(n) {
        var start = new Date().getTime();//定义起bai始时间的毫秒数
        while (true) {
            var time = new Date().getTime();//每次执行循环取得du一次当前时间的毫秒数
            if (time - start > n) {//如果当前时间的毫秒数减去起始时间的毫秒数大于给定的毫秒数，即结束循环
                break;
            }
        }
    }

    function aa() {
        var ids = [];
        $.each($('input[name=\'childclick\']:checkbox'), function () {
            if (this.checked) {
                ids.push($(this).val())
            }
        });
        if (ids.length === 0) {
            layer.msg('请选择数据查看');
            return
        }

        var url = "/mOverseeQuestions/downSource?id=" + encodeURI(JSON.stringify(ids));
        $.fileDownload(url, {
            httpMethod: 'GET',
            //同时上传表单数据
            data: '',
            prepareCallback: function (url) {
                $('#down').attr('disabled', false)
                console.log("请稍等！");
            },
            successCallback: function (url) {

                $('#down').attr('disabled', false)
                return false
            },
            failCallback: function (html, url) {
                var json = JSON.parse(html);
                console.log(json);
                $('#down').attr('disabled', false)
            }
        });
        return false
    }
    $('#down').on('click',  function () {
        aa()
    })

    $('#del').on('click', function () {
        var ids = [];
        $.each($('input[name=\'childclick\']:checkbox'), function () {
            if (this.checked) {
                ids.push($(this).val())
            }
        });

        if (ids.length === 0 || ids.length > 1) {
            layer.msg('请选择一条数据删除');
        } else {
            $.ajax({
                type: 'get',
                dataType: 'json',
                url: '/mOverseeQuestions/deleteYearReport?id=' + ids[0],
                contentType: "application/json; charset=utf-8",
                data: {},
                success: function (res) {
                    if (res.errorCode == 0) {
                        layer.msg("删除成功");
                        window.location.reload();
                    } else {
                        layer.msg(res.errorMsg);
                    }
                }
            })
        }


    })

    $("#searchBt").click(function () {
        example.ajax.reload();
    });


    init()

    function reload() {
        window.location.reload()
    }


</script>
</body>
</html>

